package com.wayz.controller;

import com.wayz.constants.CFileType;
import com.wayz.entity.pojo.UploadFileInfo;
import com.wayz.exception.WayzException;
import com.wayz.response.WayzResponse;
import com.wayz.service.AliossService;
import com.wayz.util.EncryptHelper;
import com.wayz.validator.ParameterValidator;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.MessageFormat;

/**
 * 文件控制器类
 * 
 * @author wade.liu@wayz.ai
 *
 */
@Controller
@RequestMapping("/file")
@SessionAttributes("myId")
public class FileController {

	/** 文件导入路径 */
	@Value("${shareFile.importPath}")
	private String shareFileImportPath = null;

	/** 图片上传最大限制(单位M) */
	@Value("${image.maxSize}")
	private Integer imageMaxSize = null;
	/** 音频上传最大限制(单位M) */
	@Value("${audio.maxSize}")
	private Integer audioMaxSize = null;
	/** 视频上传最大限制(单位M) */
	@Value("${video.maxSize}")
	private Integer videoMaxSize = null;

	/** 文件代理 */
	@Reference(version = "1.0.0", check=false)
	private AliossService aliossService = null;

	/**
	 * 上传文件
	 * 
	 * @param myId 我的标识
	 * @param dataFile 数据文件
	 * @param fileType 文件类型(0:其他文件; 1:用户头像; 2:媒体位; 3:广告素材; 4：数据报告; 5:公司资料;
	 *            6:效果监播)
	 * @return 云歌应答
	 * @throws WayzException 商城异常
	 * @throws IOException
	 */
	@ResponseBody
	@RequestMapping(value = "/uploadFile", method = { RequestMethod.GET, RequestMethod.POST })
	public WayzResponse uploadFile(@ModelAttribute("myId") Long myId,
								   @RequestParam(value = "dataFile", required = false) MultipartFile dataFile,
								   @RequestParam(value = "fileType", required = false) Short fileType) throws WayzException, IOException {
		// 初始化
		WayzResponse $response = new WayzResponse();

		// 验证参数
		// 验证参数: 数据文件
		ParameterValidator.notNull(dataFile, "数据文件");
		// 数据文件进行校验
		//ParameterValidator.isTrue(dataFile.getSize() > 100 * 1024 * 1024, "数据文件大小超出100M");

		// 校验图片上传大小限制
		String contentType = dataFile.getContentType();
		long fileSize = dataFile.getSize();
		if (contentType.contains("image")) {
			if (fileSize > imageMaxSize * 1024 * 1024) {
				throw new WayzException(MessageFormat.format("图片大小超出限制:{0}M", imageMaxSize));
			}
		}
		// 校验音频上传大小限制
		else if (contentType.contains("audio")) {
			if (fileSize > audioMaxSize * 1024 * 1024) {
				throw new WayzException(MessageFormat.format("音频大小超出限制:{0}M", audioMaxSize));
			}
		}
		// 校验视频上传大小限制
		else if (contentType.contains("video")) {
			if (fileSize > videoMaxSize * 1024 * 1024) {
				throw new WayzException(MessageFormat.format("视频大小超出限制:{0}M", videoMaxSize));
			}
		}

		// 保存文件
		if (fileType == null) {
			fileType = CFileType.OTHER.getValue();
		}
		File $dataFile = saveDataFile(dataFile, fileType);

		// 文件大小
		// String filePath = $dataFile.getAbsolutePath();

		// 上传文件
		UploadFileInfo uploadFileInfo = null;

		try {
			// 非线上环境发布至oss
			uploadFileInfo = aliossService.uploadFile(myId, $dataFile.getAbsolutePath(),
					dataFile.getOriginalFilename(), fileSize, contentType, fileType);

		}
		catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		finally {
			// 删除本地文件
			$dataFile.delete();
		}

		// 调用接口
		$response.setData(uploadFileInfo);

		// 返回应答
		return $response;
	}

	/**
	 * 保存数据文件
	 *
	 * @param dataFile 数据文件
	 * @return 文件对象
	 * @throws WayzException 商城异常
	 */
	private File saveDataFile(MultipartFile dataFile, Short fileType) throws WayzException {
		// 检查存在
		if (dataFile.isEmpty()) {
			throw new WayzException("文件不存在");
		}

		// 获取数据
		String fileName = dataFile.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		String dirName = shareFileImportPath + "/" + CFileType.getDirectory(fileType);

		// 创建目录
		File dir = new File(dirName);
		if (!dir.exists()) {
			dir.mkdirs();
		}

		// 保存文件
		fileName = EncryptHelper.toMD5(fileName + System.currentTimeMillis()) + suffix;
		File $dataFile = new File(dir, fileName);
		try {
			dataFile.transferTo($dataFile);
		}
		catch (IllegalStateException | IOException e) {
			throw new WayzException(MessageFormat.format("保存文件异常", e));
		}

		// 返回数据
		return $dataFile;
	}


	/**
	 * 调用STS API 获取阿里云临时安全令牌
	 *
	 * @param myId
	 * @return
	 * @throws WayzException
	 */
	@ResponseBody
	@RequestMapping(value = "/getUploadAdminToken", method = { RequestMethod.GET, RequestMethod.POST })
	public WayzResponse getUploadAdminToken(@ModelAttribute("myId") Long myId, @RequestParam(value = "fileSize", required = false) Long fileSize) throws WayzException {
		WayzResponse response = new WayzResponse();
		response.setData(aliossService.getUploadToken(null,fileSize));
		return response;
	}

}
